import React, { useEffect } from "react";
import { connect } from "react-redux";
import { setViewAction } from "../../redux/actions/viewAction";
import { loadModules, loadCss } from "esri-loader";

import Test from "../Test/Test";

import "./MyMap.css";

const MyMap = (props) => {
    const mapDom = React.createRef();

    useEffect(() => {
        loadCss(props.mapConfig.apiCssUrl);
        loadModules([
            "esri/views/SceneView",
            "esri/views/MapView",
            "esri/WebScene",
            "esri/Map",
            "esri/layers/WebTileLayer",
            "esri/layers/SceneLayer"], props.mapConfig.apiOption)
            .then(([SceneView, MapView, WebScene, Map, WebTileLayer, SceneLayer]) => {
                const wkid = props.mapConfig.wkid;

                const map = new Map();

                /* 天地图矢量图层和矢量注记图层 */
                const tk = "";// 天地图秘钥
                const baseLayer_vec = new WebTileLayer({
                    urlTemplate: `http://t{subDomain}.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={level}&TILEROW={row}&TILECOL={col}&tk=${tk}`,
                    subDomains: [0, 1, 2, 3, 4, 5, 6, 7]
                });
                const baseLayer_cva = new WebTileLayer({
                    urlTemplate: `http://t{subDomain}.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={level}&TILEROW={row}&TILECOL={col}&tk=${tk}`,
                    subDomains: [0, 1, 2, 3, 4, 5, 6, 7]
                });
                map.add(baseLayer_vec);
                map.add(baseLayer_cva);

                /* 三维场景 */
                const view = new SceneView({
                    map: map,
                    container: mapDom.current,
                    spatialReference: { wkid: wkid },
                    qualityProfile: "high",
                    extent: {
                        xmin: 113.175418,
                        ymin: 23.082685,
                        xmax: 113.389862,
                        ymax: 23.185309,
                        spatialReference: { wkid: 4326 }
                    }
                });
                props.setViewAction(view);
                // view.watch("extent", newValue => {
                //     console.log(newValue);
                // });
            });
    });

    return (
        <>
            <div ref={mapDom} className="map-outer-box" ></div>
            <Test></Test>
        </>
    );
}

const mapStateToProps = state => ({
    mapConfig: state.mapConfig
});

const mapDispatchToProps = dispatch => ({
    setViewAction: view => dispatch(setViewAction(view))
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(MyMap);